package com.jianggy.annotation;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PackageScannerImp implements PackageScanner {
	private static final Logger LOGGER = LogManager.getLogger(PackageScannerImp.class.getName());

	@Override
	public List<String> doScan(String packageName) throws URISyntaxException {
		List<String> classNameList = new ArrayList<>();
		URL url = Thread.currentThread().getContextClassLoader().getResource("");
		URI uri = new URI(url.toString() + dotReplace(packageName));
		LOGGER.info(uri);
		File file = new File(uri);
		scan(file, classNameList, packageName);
		for (Iterator iterator = classNameList.iterator(); iterator.hasNext();) {
			String className = (String) iterator.next();
			LOGGER.info(className);
		}
		return classNameList;
	}

	/**
	 * 递归扫描文件夹中的内容，并将扫描到的class文件保存到List中
	 * @time 2018年5月4日 下午6:30:46
	 * @Description
	 * @param file 制定路径的文件夹
	 * @param classNameList 保存扫描的文件
	 * @param packageName 当前对应的包名称
	 */
	private void scan(File file, List<String> classNameList, String packageName) {
		String[] names = file.list();
		try {
			for (String name : names) {
				if (isDirectry(new URI(file.toURI() + name))) {
					packageName = packageName + "." + name;
					scan(new File(new URI(file.toURI() + name)), classNameList, packageName);
				} else if (name.endsWith(".class")) {
					classNameList.add(packageName + "." + name.replace(".class", ""));
				}
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将路径中的/替换为.
	 * @time 2018年5月4日 下午6:36:13
	 * @Description
	 * @param target
	 * @return
	 */
	private String dotReplace(String target) {
		String split = "/";
		String res = target.replace(".", split);
		return res;
	}

	/**
	 * 判断URI是否是文件
	 * @time 2018年5月4日 下午6:36:40
	 * @Description
	 * @param uri
	 * @return
	 */
	private boolean isDirectry(URI uri) {
		File file = new File(uri);
		if (file != null && file.isDirectory()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 测试方法
	 * @time 2018年5月4日 下午6:36:59
	 * @Description
	 * @param args
	 * @throws URISyntaxException
	 */
	public static void main(String[] args) throws URISyntaxException {
		PackageScannerImp packageScannerImp = new PackageScannerImp();
		List<String> list = packageScannerImp.doScan("com.jianggy.annotation");

	}
}
